package com.hjt.gulimall.product.service.impl;

import com.hjt.gulimall.product.dao.CategoryBrandRelationDao;
import com.hjt.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.Query;

import com.hjt.gulimall.product.dao.BrandDao;
import com.hjt.gulimall.product.entity.BrandEntity;
import com.hjt.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {


    @Autowired
    private CategoryBrandRelationService relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wrapper.and((obj) -> {
                obj.eq("brand_id", key).or().like("name", key);
            });
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    // 更新信息
    @Override
    @Transactional
    public void updateDetail(BrandEntity brand) {
        // 保证冗余数据的一致
        // 1.更新自己的信息
        this.baseMapper.updateById(brand);
        // 2.更新冗余的数据
        if (StringUtils.hasLength(brand.getName())) {
            relationService.updateBrand(brand.getBrandId(), brand.getName());

            // TODO:更新其他关联的冗余信息
        }
    }
}